﻿using System;
using System.Globalization;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace w2.Web.Controllers
{
	public class WikiPageHandler: MvcHandler
   {
      public WikiPageHandler(RequestContext requestContext)
         : base(requestContext)
      {
      }

      protected override void ProcessRequest(HttpContext httpContext)
      {
         if(RequestContext == null)
            throw new InvalidOperationException("No RequestContext");
         try
         {
            base.ProcessRequest(httpContext);
         }
         catch(HttpException e)
         {
            if(e.GetHttpCode()==404)
            {
               var controllerFactory = ControllerBuilder.Current.GetControllerFactory();
               RequestContext.RouteData.Values["action"] = "Index";
               var controllerName = RequestContext.RouteData.GetRequiredString("controller");
               var controller = controllerFactory.CreateController(RequestContext,controllerName);
               if(controller == null)
               {
                  throw new InvalidOperationException(
                      String.Format(
                          CultureInfo.CurrentUICulture,
                          "{0} returned null for {1}",
                          controllerFactory.GetType(),
                          controllerName));
               }
               try
               {
                  controller.Execute(RequestContext);
               }
               finally
               {
                  controllerFactory.ReleaseController(controller);
               }
            }
            else
            {
               throw;
            }
         }
      }
   }
}